/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ManageBean;

import UserBN.UserService;
import entity.SwhUser;
import java.io.Serializable;
import java.util.Date;
import java.util.UUID;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.component.UIComponent;
import javax.faces.component.UIInput;
import javax.faces.context.FacesContext;
import javax.faces.validator.ValidatorException;
import javax.mail.internet.AddressException;

/**
 *
 * @author Mr-Quick
 */
@ManagedBean
@RequestScoped
public class RegisterMB implements Serializable {

    private String account;
    private String password;
    private String fullname;
    private int age;
    private java.util.Date birthday = new java.util.Date();
    private String type;
    private String email;
    private String sex;
    private String city;
    private String address;
    private String conirmpassword;

    public String getConirmpassword() {
        return conirmpassword;
    }

    public void setConirmpassword(String conirmpassword) {
        this.conirmpassword = conirmpassword;
    }

    public String getAccount() {
        return account;
    }

    public void setAccount(String account) {
        this.account = account;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getFullname() {
        return fullname;
    }

    public void setFullname(String fullname) {
        this.fullname = fullname;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public String register() {
        UserService svc = new UserService();

        SwhUser u = new SwhUser();
        u.setIDUser(UUID.randomUUID().toString());
        u.setAccount(account);
        u.setPassword(password);
        u.setFullname(fullname);
        u.setAge(age);
        u.setBirthday(birthday);
        u.setTypeUser(type);
        u.setEmail(email);
        u.setSex(sex);
        u.setCity(city);
        u.setAddress(address);
        //sendConfirmMail(email, username);
        svc.register(u);
        return "/Message.xhtml?faces-redirect=true";
    }

    public void validateEmail(
            FacesContext context,
            UIComponent componentToValidate,
            Object value)
            throws ValidatorException {
        UIInput uiInput = (UIInput) componentToValidate;
        if (uiInput.isRequired() && uiInput.isValid()) {
            String emailValue = (String) value;
            if (!emailValue.matches("^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,4}$")) {
                FacesMessage message = new FacesMessage(
                        FacesMessage.SEVERITY_ERROR,
                        "Email is invalid",
                        "Email is invalid");
                throw new ValidatorException(message);
            } else {
                UserService accountService = new UserService();
                boolean isExisted = accountService.checkExistedEmail(emailValue);
                if (isExisted) {
                    FacesMessage message = new FacesMessage(
                            FacesMessage.SEVERITY_ERROR,
                            "Email is existed",
                            "Email is existed");
                    throw new ValidatorException(message);
                } else {
                    FacesMessage message = new FacesMessage(
                            FacesMessage.SEVERITY_INFO,
                            "Email is valid",
                            "Email is valid");
                    FacesContext.getCurrentInstance().addMessage(uiInput.getId(), message);
                }
            }
        }
    }

    public void validateUserName(
            FacesContext context,
            UIComponent componentToValidate,
            Object value)
            throws ValidatorException {
        UIInput uiInput = (UIInput) componentToValidate;
        String usernameValue = value.toString();
        UserService accountService = new UserService();
        SwhUser user = accountService.findAccountByUsername(usernameValue);
        if (user != null) {
            FacesMessage message = new FacesMessage(
                    FacesMessage.SEVERITY_ERROR,
                    "Username is existed",
                    "Username is existed");
            throw new ValidatorException(message);
        }
    }

    public void validateConfirmPassword(
            FacesContext context,
            UIComponent componentToValidate,
            Object value)
            throws ValidatorException {
        UIInput passwordComponent = (UIInput) componentToValidate.getAttributes().get("passwordComponent");
        if (passwordComponent.isRequired() && passwordComponent.isValid()) {
            String passwordValue = (String) passwordComponent.getValue();
            String confirmPasswordValue = (String) value;
            if (!passwordValue.equals(confirmPasswordValue)) {
                FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Confirm password is not match", "Confirm password is not match");
                throw new ValidatorException(message);
            }
        }
    }

    public void sendConfirmMail(String email, String username) throws AddressException {
        try {
            String content = "<h2>Thank you for register with My Sweet Home </h2><br/>"
                    + "You or someone registered an account at My Sweet Home  as <span style='color:green;font-weight:bold'>" + username + "</span><br/>"
                    + "If that is not you, please do not <a href='http://localhost:8080/confirm.xhtml?id=" + username + "'>confirm</a> this email<br/>"
                    + "Have a good time<br/>";
            ProjectSettings settings = ProjectSettings.getInstance();
            MailSender.EmailSender sender = new MailSender.EmailSender();
            sender.setFrom(settings.getUsername());
            sender.setTo(new String[]{email});
            sender.setSubject("My Sweet Home : Confirm your email");
            sender.setContent(content);
            sender.setPassword(settings.getPassword());
            sender.send();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}
